<?php
namespace pay;
use  think\Request;
use   think\Config;

class Znan{

    private  $apiKey;
    private  $callback;
    private  $notify_url;
    public function __construct()
    {
            $this->class = $class = strtolower("Znan");

            $this->Config  = $Config = Config::get($class);
            $this->apiKey = $Config['apiKey']; //秘钥
            $this->mchId = $Config['mchId'];//商户号
            $this->URL = $Config['URL'];//rrl

            $domain = Request::instance()->domain();
            //curl实例
            $this->http =new \http\http();
        if(!empty($Config['callback_url'])){
            $this->callback = $Config['callback_url'];
        }else{
            $this->callback = $domain."/out/Notify/callbackurl";
            $this->pccallback = $domain."/out/Notify/pccallbackurl";
        }
        if(!empty($Config['pccallback'])){
            $this->pccallback = $Config['pccallback'];
        }
        if(!empty($Config['notify_url'])){
            $this->notify_url = $Config['notify_url'];
        }else{
            $this->notify_url =$domain."/out/Notify/handznan";
        }
        $this->notify_url2 = $domain."/out/Notify/handznandf";
    }

    public function signatureMDdf($pData){

        $sign = md5($this->mchId.$pData['amount'].$pData['pay_num'].date("Ymd").$this->apiKey);
        return $sign;
        //(merchant_no+amount+pay_num+today+key)
    }

    /**
     *  网关支付
     */
 /*   public function byPay($deposit,$payNo,$CertName,$CertNo,$Phone){



    }*/

    /**
     * @param $deposit
     * @param $payNo
     * @param $CertName
     * @param $CertNo
     * @param $Phone
     * @param $bank_code  PC 支付
     */
    public function pcPay($deposit,$payNo,$bank_code){
                    $banklist = Config::get( $this->class."_bank");
                    $pData = $this->payData($deposit,$payNo,isset($banklist[$bank_code])?$banklist[$bank_code]:"ICBC");
                    $pData['sign'] = $this->signatureMD5($pData);
                    $res = $this->createTable($pData);
                    return $res;





    }

    public function createTable2($data){
        $from = "    <form action='{$this->URL}{$this->actionList()['createDFOrder']}' id='form1'  method='post'>";
        foreach($data as $k=>$v){
            $t = "  <input name='{$k}' type='text' value='{$v}'>";
            $from .=$t;
        }
        $from .="</form>";
        return $from;
        //
    }

    public function createTable($data){
        $from = "    <form action='{$this->URL}{$this->actionList()['gate_gw_pay']}' id='form1'  method='post'>";
        foreach($data as $k=>$v){
            $t = "  <input name='{$k}' type='text' value='{$v}'>";
            $from .=$t;
        }
        $from .="</form>";
        return $from;
        //
    }


    public function createTableAPP($data){
        $from = "    <form action='{$this->URL}{$this->actionList()['hmpay']}' id='form1'  method='post'>";
        foreach($data as $k=>$v){
            $t = "  <input name='{$k}' type='text' value='{$v}'>";
            $from .=$t;
        }
        $from .="</form>";
        return $from;
        //
    }

    public function daiPay($deposit,$payNo,$account_no,$account_name,$bank_general_name,$bank_name,$phone,$id_no){

        $data = $this->daiData($deposit,$payNo,$account_no,$account_name,$bank_general_name,$bank_name,$phone,$id_no);
        $data['sign'] = $this->signatureMDdf($data);
        $res = $this->createTable2($data);
        return $res;

        /*    商户号	merchant_no
    金额	amount
    商户系统订单号	pay_num
    异步通知地址	notify_url
    验证签名	sign
    对公对私	account_prop
    账号	account_no
    账户名称	account_name
    银行通用名称	bank_general_name
    开户行名	bank_name
    开户行号（联行号）	bank_code
    清算行号	drct_bank_code
    开户行所在省	province
    开户行所在市	city
    预留手机号	phone
    证件号	id_no*/

    }


    public function daiData($deposit,$payNo,$account_no,$account_name,$bank_general_name,$bank_name,$phone,$id_no){
        $data = [
            "merchant_no"=>$this->mchId,
            "amount"=>bcmul($deposit,100),
            "pay_num"=>$payNo,
            "account_prop"=>0,
            "account_no"=>$account_no,
            "account_name"=>$account_name,
            "bank_general_name"=>$bank_general_name,
            "bank_name"=>$bank_name,
            "phone"=>$phone,
            "id_no"=>$id_no,
            "notify_url"=>$this->notify_url2,
        ];
        return $data;

    }

    /**
     * @param $deposit
     * @param $payNo
     * @param $CertName
     * @param $CertNo
     * @param $Phone
     * @param $bank_code  PC 支付
     */
    public function byPay($deposit,$payNo,$CertName,$CertNo,$Phone,$bank_no){

        $pData = $this->payDataApp($deposit,$payNo,$bank_no,$CertName,$CertNo);
        $pData['sign'] = $this->signatureMD5($pData);
        $res = $this->createTableAPP($pData);
        return $res;
    }




    public function actionList(){
        $data = [];
        $data['hmpay'] = "/hmpay/online/createWxOrder.do";
        $data['gate_gw_pay'] = "/hmpay/online/createWxOrder.do";
        $data['createDFOrder'] = "/hmpay/online/createDFOrder.do";
        return $data;
    }

    public function signatureMD5($pData){

        $sign = md5($this->mchId.$pData['total_fee'].date("Ymd").$this->apiKey);
        return $sign;
    }


    public function signatureMD52($pData){
        /*merchant_no+out_trade_no+ pay_num + total_fee +key*/
        $sign = md5($this->mchId.$pData['out_trade_no'].$pData['pay_num'].$pData['total_fee'].$this->apiKey);
        return $sign;
    }

    public function payData($deposit,$payNo,$bank_no="ICBC"){

      $data = [
          "merchant_no"=>$this->mchId,
          "total_fee"=>bcmul($deposit,100),
          "pay_num"=>$payNo,
          "productname"=>"资金充值",
          "pay_type"=>"gwpay",
/*       "card_no"=>$bank_no,
          "phone_no"=>$Phone,
          "card_name"=>$CertName,
          "id_no"=>$CertNo,*/
          "return_url"=>$this->pccallback,
          "notifyurl"=>$this->notify_url,
          "bank_code"=>$bank_no,
      ];

/*       商户号	merchant_no	必填
金额	total_fee	必填（单位分）大于0
商户自己系统订单号	pay_num	必填，保证订单号的唯一性

异步通知	notifyurl	必填 通知地址
验证签名	sign	必填，sign = MD5(merchant_no+total_fee+today+key)；today= (yyyyMMdd),当天日期，比如20160823
商品名称	productname	非必填，暂时不可用
支付类型	pay_type	必填,  微信扫码：wxpay，支付宝扫码：alipay，网关：gwpay，快捷支付（跳页面）：qkpay，公众号支付：gzhpay，微信H5：wxh5pay,支付宝H5：alih5pay，QQ扫码：qqpay,微信WAP:wxwap，快捷直连：qkapipay，银联扫码：unpay
银联卡号	card_no	快捷支付必填，其他可不传
手机号	phone_no	快捷支付必填，其他可不传
持卡人姓名	card_name	快捷支付必填，其他可不传
身份证号	id_no	快捷支付必填，其他可不传
应用类型	device_info	微信WAP必填，苹果APP :iOS_SDK；安卓APP :AND_SDK；手机网站 AND_WAP
应用名称	mch_app_name	微信WAP必填,苹果或安卓APP应用中,传对应在AppStore 和安桌分发市场中的应用名,手机网站，传对应的网站名
应用标识	mch_app_id	微信WAP必填,苹果传IOS应用唯一标识,安卓传包名,手机网站传网站首页 URL 地址
用户标识（微信用户关注商家公众号的openid）	open_id	公众号支付必填，其他不填
跳转返回页面	return_url	快捷支付，微信WAP,网关支付和H5必填，成功后跳转页面
银行编码	bank_code	非必填，网关支付使用，用于直接跳转银行网银界面，参考《网关支付银行附录》*/

     return $data;

    }    public function payDataApp($deposit,$payNo,$bank_no,$CertName,$CertNo){

      $data = [
          "merchant_no"=>$this->mchId,
          "total_fee"=>bcmul($deposit,100),
          "pay_num"=>$payNo,
          "productname"=>"资金充值",
          "pay_type"=>"qkpay",
          "card_no"=>$bank_no,
          "card_name"=>$CertName,
          "id_no"=>$CertNo,
          "return_url"=>$this->pccallback,
          "notifyurl"=>$this->notify_url,

      ];
    /*card_no, card_name, id_no*/

/*       商户号	merchant_no	必填
金额	total_fee	必填（单位分）大于0
商户自己系统订单号	pay_num	必填，保证订单号的唯一性

异步通知	notifyurl	必填 通知地址
验证签名	sign	必填，sign = MD5(merchant_no+total_fee+today+key)；today= (yyyyMMdd),当天日期，比如20160823
商品名称	productname	非必填，暂时不可用
支付类型	pay_type	必填,  微信扫码：wxpay，支付宝扫码：alipay，网关：gwpay，快捷支付（跳页面）：qkpay，公众号支付：gzhpay，微信H5：wxh5pay,支付宝H5：alih5pay，QQ扫码：qqpay,微信WAP:wxwap，快捷直连：qkapipay，银联扫码：unpay
银联卡号	card_no	快捷支付必填，其他可不传
手机号	phone_no	快捷支付必填，其他可不传
持卡人姓名	card_name	快捷支付必填，其他可不传
身份证号	id_no	快捷支付必填，其他可不传
应用类型	device_info	微信WAP必填，苹果APP :iOS_SDK；安卓APP :AND_SDK；手机网站 AND_WAP
应用名称	mch_app_name	微信WAP必填,苹果或安卓APP应用中,传对应在AppStore 和安桌分发市场中的应用名,手机网站，传对应的网站名
应用标识	mch_app_id	微信WAP必填,苹果传IOS应用唯一标识,安卓传包名,手机网站传网站首页 URL 地址
用户标识（微信用户关注商家公众号的openid）	open_id	公众号支付必填，其他不填
跳转返回页面	return_url	快捷支付，微信WAP,网关支付和H5必填，成功后跳转页面
银行编码	bank_code	非必填，网关支付使用，用于直接跳转银行网银界面，参考《网关支付银行附录》*/

     return $data;
    }


    public function Notify($result){
        $files = "/home/wwwlogs/controller_Notify_zhongnan.log";
        $tdata = ["msg"=>"异常","status"=>0,"data"=>[]];
        $arr = ["return_code","out_trade_no","trade_result","message","pay_num","total_fee"];
        //$arr = ksort($arr);signature

        if(getOS()=="Linux"){
            error_log($result.PHP_EOL,3,$files);
        }
        $result = parse_str($result, $arrs);

        if(empty($arrs)){
            return array_merge($tdata,['status'=>0,"msg"=>"通知"]);
        }
        $result = $arrs;
///hmpay/online/createWxOrder.do
       // $result = json_decode($result,true);

  /*      return_code
out_trade_no
trade_result
message
pay_num
total_fee
sign*/


        if($result['trade_result']!="success"){ //充值成功
            // 回滚事务
            if(getOS()=="Linux"){
                error_log("订单号".$result['pay_num']."已被银行折返",3,$files);
            }
            return array_merge($tdata,['status'=>0,"msg"=>"改订单已被银行折返"]);
        }


        if($result['return_code']!='10000'){
            return array_merge($tdata,['status'=>0,"msg"=>"改订单已被银行折返"]);
        }


        $darr = [];
        foreach ($result as $k=>$v){
                if(!empty($v)&&in_array($k,$arr)){
                    $darr[$k] = $v;
                }
        }
        ksort($darr);//字典排序
        $signature = $this->signatureMD52($darr);

        if(strtoupper($signature) !=strtoupper($result['sign']) ){//
            if(getOS()=="Linux"){
                error_log("订单号".$result['pay_num']."签名失败",3,$files);
            }
            return array_merge($tdata,["msg"=>"签名失败"]);
        }
        $NotifySignModel  = new \app\admin\model\UsersRecharge();
        $res = $NotifySignModel->where("thirdparty_payno",$result['pay_num'])->find();
        if($res['status']==2){
            if(getOS()=="Linux"){
                error_log("订单号".$result['pay_num']."已失效",3,$files);
            }
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已失效"]);
        }
        if($res['status']==1){
            if(getOS()=="Linux"){
                error_log("订单号".$result['pay_num']."已充值成功",3,$files);
            }
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已充值成功"]);
        }
        $resultBa['app_id'] =$result['pay_num'];
        $resultBa['three_app_id'] =$result['out_trade_no'];
        $resultBa['amount'] =$result['total_fee'];

        return  ["data"=>$resultBa,"status"=>1,"msg"=>"验证成功"];


    }








    /**
     *   生成签名
     */
    public function signature($data){
        ksort($data);//字典排序
        $dataString = "";
        foreach($data as $k=>$v){
            $dataString .=$k."=".$v."&";
        }
        $stringSignTemp =  $dataString."key=".$this->apiKey;
        $md5String = strtoupper(md5($stringSignTemp));
        return $md5String;
    }




    /**
     * @return array 获取那个基本参数
     */
    private function baseData(){
       $data = [
           "mchId"=>$this->mchId,
           "timestamp"=>date("YmdHis")."000",
           "data"=>"",
       ];
        return $data;
    }





}
?>
